#include "Socket.h"
#include "Tracer.h"
#include "FileUtil.h"
#include "StrUtil.h"
#include "ArgUtil.h"
#include "DateTime.h"
#include "Coroutine.h"
#include "Thread.h"
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>

using namespace libemb;

class CoroutinePing:public Coroutine{
public:
	void routine()
	{
		while(isRunning())
		{
			TRACE_CYAN("coroutine ping... [%s]\n",CSTR(DateTime::currentDateTime().toString()));
			msleep(1000);
			//yield();
		}
	}
};

class CoroutinePong:public Coroutine{
public:
	void routine()
	{
		while(isRunning())
		{
			TRACE_GREEN("coroutine pong... [%s]\n",CSTR(DateTime::currentDateTime().toString()));
			msleep(2000);
			//yield();
		}
	}
};


int main(int argc, char* argv[])
{
	std::string argValue;
	ArgOption  argOption;
	Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	argOption.addOption("h", 0);	/* -h:帮助 */
	argOption.parseArgs(argc,argv);	/* 解析参数 */

	if(argOption.getValue("h", argValue))
	{
		TRACE_YELLOW("coroutine help:\n");
		TRACE_YELLOW("coroutine [-h]\n");
		return RC_OK;
	}

	CoScheduler scheduler;
	std::shared_ptr<CoroutinePing> coPing = std::make_shared<CoroutinePing>();
	std::shared_ptr<CoroutinePong> coPong = std::make_shared<CoroutinePong>();
	int coPingID = coPing->coroutineID();
	int coPongID = coPong->coroutineID();
	TRACE_DBG("pingID:%d, pongID:%d\n",coPingID,coPongID);	
	scheduler.start(coPing);
	scheduler.start(coPong);

	#if 1
	/* 在主进程调度协程 */
	while(1)
	{
		scheduler.schedule(coPingID);
		scheduler.schedule(coPongID);
	}
	#else
	/* 使用子线程中自动调度 */
	Thread schedThread;
	schedThread.start(&scheduler);
	while(1)
	{
		Thread::msleep(1000);
	}
	#endif
    return 0;
}
